package com.woniuxy.oa.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class BirthdayToAgeUtil {
	
	public static  int getAge(String birthday) throws Exception {
		Date birthDate = CurrentDateUtils.stringToDateWithoutTime(birthday);
        Calendar cal = Calendar.getInstance(); 
        if (cal.before(birthDate)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDate); 
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);  
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            }else{
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age; 
	}
	/**
	 * 以虚岁计算范围，两头取闭区间，即生日当天算两个年龄。返回开始和结束日期的数组，开始日期在前；年龄不合法则返回空数组*/
	public static String[] getDateRangeByAge(Integer beginAge, Integer endAge) {
		String[] dates = new String[2];
		if(!validAge(beginAge) || !validAge(endAge)) {
			return dates;
		}
		Calendar cal = Calendar.getInstance(); 
		int range = beginAge - endAge;
		if(range < 0) {
			//startAge更小，得到的日期更大
			cal.add(Calendar.YEAR, -beginAge);
			dates[1] = CurrentDateUtils.dateToString(cal.getTime());
			//虚岁加一年
			cal.add(Calendar.YEAR, range + 1);
			dates[0] = CurrentDateUtils.dateToString(cal.getTime());
		}else {
			cal.add(Calendar.YEAR, -beginAge);
			dates[0] = CurrentDateUtils.dateToString(cal.getTime());
			cal.add(Calendar.YEAR, range + 1);
			dates[1] = CurrentDateUtils.dateToString(cal.getTime());
		}
		return dates;
	}
	public static boolean validAge(Integer age ) {
		if(age != null && age >=0 && age <= 200) {
			return true;
		}
		return false;
	}

}
